package com.pkk.spring.cloud.service.gateway.route;

import java.util.List;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import reactor.core.publisher.Flux;

/**
 * 建议的路由定义仓库
 *
 * @author peikunkun
 * @version V1.0
 * @date 2021-01-15 18:18
 **/
public abstract class AdviceRouteDefinitionRepository implements RouteDefinitionRepository,
    ApplicationEventPublisherAware, InitRouteDefinitionInterface {


  protected ApplicationEventPublisher applicationEventPublisher;


  /**
   * 获取路由定义信息
   *
   * @return reactor.core.publisher.Flux<org.springframework.cloud.gateway.route.RouteDefinition>
   * @author peikunkun
   * @date 2021/1/23 0023 上午 10:39
   */
  @Override
  public Flux<RouteDefinition> getRouteDefinitions() {
    return Flux.fromIterable(getRouteDefinitionList());
  }

  /**
   * 获取路由定义信息
   *
   * @return java.util.List<org.springframework.cloud.gateway.route.RouteDefinition>
   * @Param
   * @author peikunkun
   * @date 2021/1/23 0023 上午 10:38
   * @since
   */
  protected abstract List<RouteDefinition> getRouteDefinitionList();


  /**
   * Set the ApplicationEventPublisher that this object runs in.
   * <p>Invoked after population of normal bean properties but before an init
   * callback like InitializingBean's afterPropertiesSet or a custom init-method.
   * Invoked before ApplicationContextAware's setApplicationContext.
   *
   * @param applicationEventPublisher event publisher to be used by this object
   */
  @Override
  public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
    this.applicationEventPublisher = applicationEventPublisher;
  }


  /**
   * 更新路由
   *
   * @return boolean
   * @Param definitions
   * @author peikunkun
   * @date 2021/1/22 0022 下午 6:05
   * @since
   */
  public abstract boolean update(List<RouteDefinition> definitions);


  /**
   * 刷新路由改变通知
   *
   * @return void
   * @Param
   * @author peikunkun
   * @date 2021/1/22 0022 下午 5:54
   * @since
   */
  public void notifyChanged() {
    this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
  }


}
